import { Message } from "element-ui";

const state = {
  isAuthenticated: false, // 用户是否已验证
  needAuthenticateTime: null, // 账号需要验证的时间
  timeout: null, // 计时器
  cleanupListeners: null, // 保存清理事件监听的函数
  needAuthenticateUserEvents:[], // 需要验证用户事件
};

const getters = {
  isAuthenticated: (state) => state.isAuthenticated,
};

const mutations = {
  SET_AUTHENTICATED(state, value) {
    state.isAuthenticated = value;
  },
  SET_TIMEOUT(state, timeout) {
    state.timeout = timeout;
  },
  SET_CLEANUP_LISTENERS(state, cleanupFunction) {
    state.cleanupListeners = cleanupFunction;
  },
  // 添加移除事件
    addNeedAuthenticateUserEvent(state, event) {
        state.needAuthenticateUserEvents.push(event)
    },
    removeNeedAuthenticateUserEvent(state, event) {
        const index = state.needAuthenticateUserEvents.indexOf(event)
        if (index !== -1) {
            state.needAuthenticateUserEvents.splice(index, 1)
        }
    }
};

const actions = {
  // 设置用户认证状态
  authenticateUser({ commit, dispatch }, value) {
    console.log("authenticateUser 被调用，认证状态：", value);

    commit("SET_AUTHENTICATED", value);

    if (value) {
        // unknown local action type: auth/resetTimer, global type: auth/auth/resetTimer
      dispatch("_resetTimer");
      dispatch("_setupActivityListeners");
    }
  },
  // 重新开始认证状态(指定时间)
    reStartAuthenticateUserTime({ commit, dispatch }, needAuthenticateTime) {
        console.log("重新开始指定时间的验证：", needAuthenticateTime);

        if (needAuthenticateTime) {
            if (new Date() >= needAuthenticateTime) {
                // 直接设置未验证
                commit("SET_AUTHENTICATED", false);
                return;
            }
            else {
                commit("SET_AUTHENTICATED", true);
                const timeLimit = needAuthenticateTime - new Date();
                
                dispatch("_resetTimer", timeLimit);
                dispatch("_setupActivityListeners");
            }
        }
    },
    // 发送需要账户验证的事件
    sendNeedAuthenticateUserEvent({state},args){
        console.log('发送请求认证的事件')
        state.needAuthenticateUserEvents.forEach(e => e(args));
    },
  // 注销并清除定时器和事件监听
  logout({ commit, state }) {
    commit("SET_AUTHENTICATED", false);
    if (state.timeout) {
      clearTimeout(state.timeout);
    }

    // 清理事件监听
    if (state.cleanupListeners) {
      window.removeEventListener("beforeunload", state.cleanupListeners);
      state.cleanupListeners();
    }
  },

  // 重置定时器
  _resetTimer({ state, commit }, timeLimit) {
    if (state.timeout) {
      clearTimeout(state.timeout);
        state.timeout=0;
    }

      let TIME_LIMIT = timeLimit || (10 * 60 * 1000); // 默认 10分钟
      
      const needAuthenticateTime = new Date() + TIME_LIMIT;
      // 保存需要验证的时间
      state.needAuthenticateTime = needAuthenticateTime;
      localStorage.setItem('needAuthenticateInfo',JSON.stringify({
          needAuthenticateTime
      }))


    const timeout = setTimeout(() => {
      commit("SET_AUTHENTICATED", false); // 超时后设置为未验证
    //   Message.info("您已超过10分钟未操作，若修改数据需重新验证账号！");
    }, TIME_LIMIT);

    commit("SET_TIMEOUT", timeout);
  },

  // 设置活动监听
  _setupActivityListeners({ commit, dispatch }) {
    console.log("setupActivityListeners 被调用");

    const resetTimeout = () => {
      console.log("活动事件触发，重置定时器");
      dispatch("_resetTimer"); // 重置定时器
    };

    document.addEventListener("mousemove", resetTimeout);
    // document.addEventListener("keydown", resetTimeout);

    const cleanupListeners = () => {
      document.removeEventListener("mousemove", resetTimeout);
    //   document.removeEventListener("keydown", resetTimeout);
    };

    commit("SET_CLEANUP_LISTENERS", cleanupListeners);

    window.addEventListener("beforeunload", cleanupListeners);
  },

};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};
